<template>
  <div>
    <div class="input-area">
      <textarea v-model="inputText" rows="4" placeholder="请输入内容..."></textarea>
      <button @click="sendMessage">发送</button>
    </div>
    <div class="output-area">
      {{ outputText }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';

export default {
  name: 'App',
  components: {
  },
  setup() {
    const inputText = ref('');
    const outputText = ref(''); // 原始流式数据


    let eventSource = null;

    // 处理流式数据并渲染为HTML
    const handleStream = (data) => {
      outputText.value += data;
    };

    // 发送消息并建立连接
    const sendMessage = async () => {
      if (!inputText.value.trim()) return;

      // 清空之前的输出
      outputText.value = '';

      try {
        const response = await fetch('http://localhost:5000/chat', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ content: inputText.value }),
        });

        if (!response.ok) {
          throw new Error(`Network response was not ok. Status: ${response.status}`);
        }

        const reader = response.body.getReader();
        /* eslint-disable no-constant-condition */
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          const chunk = new TextDecoder().decode(value);
          console.log('Received chunk:', chunk);
          handleStream(chunk);
        }
      } catch (error) {
        console.error('Fetch Error:', error);
        outputText.value = `连接失败，请重试！错误信息: ${error.message}`;
      }
    };

    // 生命周期钩子：组件挂载时初始化
    onMounted(() => {
    });

    // 生命周期钩子：组件卸载前关闭连接
    onBeforeUnmount(() => {
      if (eventSource) {
        eventSource.close();
        eventSource = null;
      }
    });

    return {
      inputText,
      outputText,
      sendMessage,
    };
  },
};
</script>

<style>
.input-area {
  margin: 20px;
}

textarea {
  width: 80%;
  padding: 10px;
  font-size: 16px;
}

button {
  margin-left: 10px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}

.output-area {
  margin: 20px;
  padding: 20px;
  border: 1px solid #ccc;
  min-height: 300px;
  white-space: pre-wrap;
  font-family: monospace;
}

/** Marked.css (可选美化) */
/* 你可以添加额外的样式来美化Markdown渲染 */
</style>
